#!-*- encoding:utf8 -*-
from django.conf.urls.defaults import *
from django.contrib import admin
from django.template import Template, Context, RequestContext
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponseRedirect, HttpResponse
from newosmp import settings
from newosmp.users.models import UserProfile
from newosmp.flow.models import Flow
from newosmp import settings
from newosmp.host.models import Host, Product, IDC
from newosmp.monitor.models import Monitor
from newosmp.alert.models import Alert
from django.contrib.auth.decorators import user_passes_test, login_required
from django.db.models import  Sum
import datetime
admin.autodiscover()

@login_required
def index(request):
    """
    首页的信息汇总
    主机概要
    监控概要
    今日报警
    今日任务
    当前用户信息
    当前服务状态信息
    当前警报状态信息
    当前可用率信息
    """
    
    #主机
    hcount = Host.objects.count()
    icount = IDC.objects.count()
    thcount = Host.objects.filter(status="T").count()
    fhcount = hcount - thcount
    #监控
    mcount = Monitor.objects.count()
    tmcount = Monitor.objects.filter(status="T").count()
    fmcount = mcount - tmcount
    #报警[今日]
    acount = Alert.objects.all()
    
    all = {
           'hcount':hcount,'icount':icount,'thcount':thcount,'fhcount':fhcount,
           'mcount':mcount,'tmcount':tmcount,'fmcount':fmcount
           }
    
    request.session['all'] = all
    
    #利用率
    host_total = Host.objects.count()
    host_error = Host.objects.filter(status='F').count()
    host_normal = host_total - host_error
 
    host_cores = 1
    host_load = 0
    hosts = Host.objects.annotate(load=Sum('r_load'), cores=Sum('r_cpu_core'))
    if len(hosts) > 0:
        host_cores = hosts[0].cores
        host_load = hosts[0].load
    if host_cores < 0:
        usage = "00.00"
    else:
        usage = "%.2f" % (float(host_load) * 100 / host_cores) 
    if host_total == 0:
       avail = "%.2f" % 100
    else:
        avail = "%.2f" % (float(host_normal) * 100 / host_total)

    return render_to_response("index.html", locals())

urlpatterns = patterns('',
    (r'^$', index),
    (r'^index/', index),
    (r'^admin/', include(admin.site.urls)),
    (r'^flow/', include('newosmp.flow.urls')),
    (r'^host/', include('newosmp.host.urls')),
    (r'^wiki/', include('newosmp.wiki.urls')),
    (r'^users/', include('newosmp.users.urls')),
    (r'^alert/', include('newosmp.alert.urls')),
    (r'^group/', include('newosmp.group.urls')),
    (r'^report/', include('newosmp.report.urls')),
    (r'^monitor/', include('newosmp.monitor.urls')),
    (r'^accounts/', include('newosmp.accounts.urls')),
    (r'^strategy/', include('newosmp.strategy.urls')),
    (r'^service/', include('newosmp.service.urls')),
    (r'^wiki/', include('newosmp.wiki.urls')),
#    (r'^doc/', include('newosmp.document.urls')),
#    (r'^accident/', include('newosmp.accident.urls')),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
